package demo.security;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import demo.security.error.DemoWebResponseExceptionTranslator;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Autowired
//	@Qualifier("MyTokenStore")
//	@Qualifier("JwtTokenStore")
	private TokenStore tokenStore;
	
	@Autowired
//	@Qualifier("MyAccessTokenConverter")
//	@Qualifier("JwtAccessTokenConverter")
	private AccessTokenConverter accessTokenConverter;
	
	@Autowired
//	@Qualifier("MyTokenEnhancer")
//	@Qualifier("JwtTokenEnhancer")
	private TokenEnhancer tokenEnhancer;
	
	@Autowired
	private ClientDetailsService clientDetailsService;
	
	@Bean	
	public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(this.clientDetailsService);	
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

		endpoints.tokenServices(defaultTokenServices());
		
		endpoints.authenticationManager(this.authenticationManager);
		
		endpoints.tokenStore(this.tokenStore)
				.accessTokenConverter(this.accessTokenConverter)
				.tokenEnhancer(tokenEnhancer);
		
		endpoints.exceptionTranslator(new DemoWebResponseExceptionTranslator());
	}

	@Primary
	@Bean
	public DefaultTokenServices defaultTokenServices() {
		DefaultTokenServices tokenServices = new DefaultTokenServices();
		tokenServices.setTokenStore(tokenStore);
		tokenServices.setTokenEnhancer(this.tokenEnhancer);
		tokenServices.setSupportRefreshToken(true);
		tokenServices.setClientDetailsService(clientDetailsService);
		tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.SECONDS.toSeconds(30)); 
		tokenServices.setRefreshTokenValiditySeconds((int) TimeUnit.SECONDS.toSeconds(60 * 30)); 
		return tokenServices;
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {		
		oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
	}
	
//	@Configuration
//	protected static class WebMvcConfig implements WebMvcConfigurer {
//		@Override
//		public void addViewControllers(ViewControllerRegistry registry) {
//    		registry.addViewController("/login").setViewName("customized_login"); //login page
//			registry.addViewController("/oauth/confirm_access").setViewName("customized_confirm_access");			
//		}
//	}
}
